package com.server;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.db.DB;
import com.tools.Constants;
import com.tools.Files;

public class C2S7News extends HttpServlet {
	@Override
	public  void init() throws ServletException {
		Constants.init();
		System.out.println("DB name:" + Constants.DBNAME);
		DB.connDB();
		super.init();
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String e_id = null;
	String e_score1 = null;
	String e_total_reply_count1 = null;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		Enumeration<String> er = request.getParameterNames();
		System.out.println("[vswb7] whitebox7 get begin");
		System.out.println("版本> 14");
		PrintWriter writer = response.getWriter();
		String e_user_id = null;
		String e_id = null;
		String e_story = null;
		String e_img_path = null;
		String e_score = null;
		String r_story = null;
		
		while (er.hasMoreElements()) {
			String element = er.nextElement();
			if (element.equals("e_user_id")) {
				e_user_id = request.getParameterValues("e_user_id")[0];
				System.out.println("[vswb7] e_user_id:"+e_user_id);
			}
			if (element.equals("e_id")) {
				e_id = request.getParameterValues("e_id")[0];
				System.out.println("[vswb 7] e_id:"+e_id);
			}
			if (element.equals("e_story")) {
				e_story = request.getParameterValues("e_story")[0];
			}
			if (element.equals("e_img_path")) {
				e_img_path = request.getParameterValues("e_img_path")[0];
			}

			if (element.equals("e_score")) {
				e_score = request.getParameterValues("e_score")[0];
			}
			
			if (element.equals("r_story")) {
				r_story = request.getParameterValues("r_story")[0];
			}
			
		}
		
		if((e_id != null) && (r_story != null) && (r_story.equals("all"))){
			ResultSet rs = DB.select("select * from reply where e_id='"+e_id+"' order by r_time desc; ") ;
			try{
				while(rs.next()){
					String r_reply1 = rs.getString("r_story");
					String r_time1 = rs.getString("r_time");
					if((r_reply1 == null) || (r_reply1.length() == 0) || (r_reply1.equals(""))){
						continue;
					}
					writer.println(r_reply1+"僫"+r_time1+"峩");
				}
			}catch(Exception e5){
				e5.printStackTrace();
			}
		}
		
		if ((e_user_id != null) && (e_id != null) && (e_score != null) &&(e_score.equals("true"))&&(!e_id.equals("EID") && (!e_id.equals("all")))){
			ResultSet rs =DB.select("select e_score from event where e_user_id='"+e_user_id+"' and e_id='"+e_id+"';");
			int temp = new Integer(0);
			try{
				while(rs.next()){
					String  e_score4 = rs.getString("e_score");
					temp = Integer.valueOf(e_score4) + 1;
					System.out.println("[vswb7] tempReplyCount:"+temp);
					e_score4= null;
				}
			}catch(Exception e6){
				e6.printStackTrace();
			}
			DB.exeCmd("update event set e_score='"+String.valueOf(temp)+"' where e_user_id='"+e_user_id+"' and e_id='"+e_id+"';");
			DB.exeCmd("update event set e_last_r_time=now() where e_user_id='"+e_user_id+"' and e_id='"+e_id+"';");
			e_score = null;
			System.out.println("update up success!");
			writer.println("ok");
		}
		if ((e_user_id != null) && (e_id != null) && (!e_id.equals("EID") && (!e_id.equals("all")))){
				
					ResultSet rs = DB.select("select * from event where e_user_id='" + e_user_id + "' order by e_create_time desc limit 0,1;");
				
					try {
						while (rs.next()) {
							String e_id1 = rs.getString("e_id");
							String e_user_id1 = rs.getString("e_user_id");
							String e_img_path1 = rs.getString("e_img_path");
							String e_story1 = rs.getString("e_story");
							String e_score1 = rs.getString("e_score");
							String e_total_reply_count1 = rs.getString("e_total_reply_count");
							String e_create_time1 = rs.getString("e_create_time");
							String e_last_r_time1 = rs.getString("e_last_r_time");
							writer.println(e_id1 + "僫" + e_user_id1+"僫"+e_img_path1 + "僫" + e_story1 + "僫" + e_score1 + "僫" + e_total_reply_count1 + "僫" + e_create_time1 + "僫" + e_last_r_time1);
						}
					} catch (SQLException e) {
						e.printStackTrace();
					}
		}
		
		if((e_user_id != null) && (e_id != null) && (e_id.equals("all"))){
			System.out.println("client request all event.");
			ResultSet rs =  DB.select("select * from event order by e_last_r_time desc;");
			try{
				while(rs.next()){
					String e_id2 = rs.getString("e_id");
					String e_user_id2 = rs.getString("e_user_id");
					String e_img_path2 = rs.getString("e_img_path");
					String e_story2 = rs.getString("e_story");
					String e_score2 = rs.getString("e_score");
					String e_total_reply_count2 = rs.getString("e_total_reply_count");
					String e_create_time2 = rs.getString("e_create_time");
					String e_last_r_time2 = rs.getString("e_last_r_time");
					writer.println(e_id2 + "僫" + e_user_id2 + "僫" + e_img_path2 + "僫" + e_story2 + "僫" + e_score2 + "僫" + e_total_reply_count2 + "僫" + e_create_time2 + "僫" + e_last_r_time2 + "峩");
				}
			}catch(Exception e1){
				e1.printStackTrace();
			}
		}
	}
				


	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		Enumeration<String> er = request.getParameterNames();
		System.out.println("[vswb7] whitebox7 post begin");
		PrintWriter writer = response.getWriter();

		String e_id = null;
		String e_id_temp = null;
		String e_user_id = null;
		String e_img_path = null;
		String e_story = null;
		String r_story = null;
		String r_user_id = null;
		
		while (er.hasMoreElements()) {
			String element = er.nextElement();
			System.out.println("[C2S7News] element:"+element);
			if (element.equals("e_user_id")) {
				e_user_id = request.getParameterValues("e_user_id")[0];
				System.out.println("e_user_id:"+e_user_id);
			}
			if (element.equals("e_img_path")) {
				e_img_path = request.getParameterValues("e_img_path")[0];
				System.out.println("e_img_path:"+e_img_path);
			}
			if (element.equals("e_story")) {
				e_story = request.getParameterValues("e_story")[0];
				System.out.println(e_story);
			}
			if (element.equals("e_id")) {
				e_id = request.getParameterValues("e_id")[0];
				System.out.println("e_id:"+e_id);
			}
			
			if (element.equals("r_story")) {
				r_story = request.getParameterValues("r_story")[0];
				System.out.println("r_story:"+r_story);
			}
			
			if (element.equals("r_user_id")) {
				r_user_id = request.getParameterValues("r_user_id")[0];
				System.out.println("r_user_id:"+r_user_id);
			}

		}
		
		if ((e_user_id != null) && (e_id != null) && (r_story != null)){
			DB.exeCmd("insert into reply(e_id,r_user_id,r_story,r_time) values('"+e_id+"','"+r_user_id+"','"+r_story+"',now());");
			DB.update("update event set e_last_r_time=now() where e_id='"+e_id+"';");
		}
		// 存在用户
		if ((e_user_id != null) && (r_story == null)){
			System.out.println("the e_user_id:"+e_user_id+" is exists,go into create event!");
			// 寻找事件e_id
			ResultSet rs = DB.select("select e_id from event  order by e_create_time desc limit 0,1;");
			try {
				
				while (rs.next()) {
					e_id_temp = rs.getString("e_id");
					System.out.println("the e_user_id:"+e_user_id+" own last event "+e_id_temp);
					// 如果事件e_id等于null，赋值为0
					if (e_id_temp == null) {
						e_id_temp = "0";
						System.out.println("e_id_temp is NULL,change it to 0");
					}
					
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if(e_id_temp == null){
				e_id_temp = "0";
				System.out.println("e_user_id:"+e_user_id+"is the first create event.give the event e_id 0 to gay.");
			}
			System.out.println("begin to judge e_id:"+e_id);
			// 如果事件e_id为空或者0
			if(e_id.equals("EID") || (e_id.equals("0"))){
				// DB.insert
				// 事件e_id_temp 加1
				int _id = Integer.valueOf(e_id_temp) + 1;
				e_id_temp = String.valueOf(_id);
				System.out.println("e_id equals EID or 0,so create the first event to "+e_user_id+",the e_id:"+e_id_temp);
				
				// 如果故事不为空 插入此新事件到event表并且创建事件
				if (e_story != null) {
					System.out.println("the event "+e_id_temp+" have story" + e_story);
					DB.exeCmd("insert into event(e_id,e_user_id,e_story,e_score,e_total_reply_count,e_create_time,e_last_r_time) values('" + e_id_temp + "','" + e_user_id + "','" + e_story + "','0','0',now(),now());");
					System.out.println("return to client the e_id:"+e_id_temp);
					writer.println(e_id_temp);
					e_id_temp = null;
					e_id = null;
					e_story = null;
					e_img_path = null;
					e_user_id = null;
					return;
				}else{
					System.out.println("the event "+e_id_temp+" not have story");
				}
				
				// 如果图片不为空 插入此新图片到event表并且创建事件
				if ((e_img_path != null) && (e_img_path.equals("true")) ){
					System.out.println("the event have e_img_path" + e_img_path);
					InputStream is = request.getInputStream();
					if (is != null) {
						if (Files.createFileDir(Constants.tomcatSrcPath)) {
							if (Files.saveFile(is, Constants.tomcatSrcPath + "e"+e_id_temp +"u"+e_user_id +  ".jpg")) {
									String img_path_temp = "http://" +Constants.SERVER_ADDRESS + ":8089/tom/res/img/e" + e_id_temp +"u"+e_user_id + ".jpg";
									DB.exeCmd("insert into event(e_id,e_user_id,e_img_path,e_score,e_total_reply_count,e_create_time,e_last_r_time) values('" + e_id_temp + "','" + e_user_id + "','" + img_path_temp + "','0','0',now(),now());");
									writer.println(e_id_temp);
									System.out.println("return to client e_id:"+e_id_temp);
									e_id = null;
									e_user_id = null;
									e_img_path = null;
									e_id_temp = null;
									e_story = null;
							}
						}
					}
				}else{
					System.out.println("the event not have e_img_path");
				}
			
			}else {
				
				// DB.update
				
				// 如果事件e_id为正常e_id,判断是否是当前事件e_id
				System.out.println("the e_user_id:"+e_user_id+" alreay create event,the gay has add something.");
				System.out.println("e_img_path:"+e_img_path);
				System.out.println("e_story:"+e_story);
					// 如果是当前事件e_id并且有图片 更新图片地址
					if ((e_img_path != null) && (e_img_path.equals("true"))) {
						System.out.println("already create event,update e_img_path begin.");
						InputStream is = request.getInputStream();
						if (is != null) {
							if (Files.createFileDir(Constants.tomcatSrcPath)) {
								File dest = new File(Constants.tomcatSrcPath + "e" +e_id +"u"+ e_user_id + ".jpg");
								System.out.println("update e_img_path ok1");
								//if (dest.exists()) {
									//dest.delete();
									//System.out.println("update e_img_path ok2");
									if (Files.saveFile(is, Constants.tomcatSrcPath + "e" +e_id +"u"+ e_user_id + ".jpg")) {
										String img_path_temp = "http://" +Constants.SERVER_ADDRESS + ":8089/tom/res/img/e" + e_id +"u"+ e_user_id + ".jpg";
										DB.update("update event set e_img_path='" + img_path_temp + "' where e_user_id='" + e_user_id + "' and e_id='"+e_id+"';");
										DB.update("update event set e_create_time=now() where e_user_id='" + e_user_id + "' and e_id='"+e_id+"';");
										writer.println(e_id);
										e_id = null;
										e_user_id = null;
										e_id_temp = null;
										e_story = null;
										e_img_path = null;
										System.out.println("update e_img_path ok");
									}
								//} 
							}
						}
					}
					
					// 如果事件e_id为正常e_id并且有故事 更新故事
					if(e_story != null){
						System.out.println("already create event,update e_story begin.");
						DB.exeCmd("update event set e_story='"+e_story+"' where e_user_id='" + e_user_id + "' and e_id='"+e_id+"';");
						writer.println(e_id);
						System.out.println("update story success.");
						e_id = null;
						e_user_id = null;
						e_story = null;
						e_img_path = null;
						e_id_temp = null;
					}
			}
			

		}
	}
	
	
}
